<template>
  <div class="login">
    <div class="bg">
    </div>
    <Modal class="login-modal" v-model="loginModal" width="360" :closable="false" :mask-closable="false">
      <div>
        <h2 style="margin:10px;color:#abcdef;text-align:center">
          人脸识别认证系统</h2>

        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate">
          <Form-item prop="name">
            <Input v-model="formValidate.name" placeholder="请输入姓名"></Input>
          </Form-item>
          <Form-item prop="password">
            <Input v-model="formValidate.password" @keyup.native.enter="handleSubmit('formValidate')" type="password" placeholder="请输入密码"></Input>
          </Form-item>
          <Row>
            <Col span="12">
            <Checkbox-group v-model="formValidate.remember">
              <Checkbox label="记住我(24小时免登录)"></Checkbox>
            </Checkbox-group>
            </Col>
            <Col span="12">
            <a style="float:right" @click="toRegister">新用户注册</a>
            </Col>
          </Row>

        </Form>
      </div>

      <div slot="footer" style="text-align: center;display:block">
        <Button type="primary" icon="log-in" :loading="modal_loading" @click="handleSubmit('formValidate')">登录
        </Button>
        <Button type="error"  icon="android-cancel"  @click="handleSubmit('formValidate')">重置
        </Button>
        <Button type="info"  icon="ios-person"  @click="faceLogin()">人脸识别
        </Button>
        <small style="text-align: center;display:block;margin-top:10px;" class="subText">©copyright by基于机器学习的人脸识别认证系统项目小组</small>
      </div>

    </Modal>
    <Modal
        v-model="faceresult"
        title="本次扫描结果"

        :scrollable="true"
       :mask-closable="true" :closable="false" style="text-align:center">
      <Table :columns="columns1" :data="facedata"></Table>
    </Modal>


    <Modal
        v-model="modal1"
        title="请查看摄像头"
        @on-ok="ok"
        :scrollable="true"
        @on-cancel="cancel" :mask-closable="true" :closable="false" style="text-align:center">
        <div>
          <label style="color:red">初始化摄像头!若浏览器提示，请点击允许！</label>
        <video id="video" width="320" height="240" :class="imgData==null?'display':'nodisplay'" autoplay></video>
        <canvas id="canvas" width="320" height="240" :class="imgData!=null?'display':'nodisplay'"></canvas>
        </div>
        <Row>
      <Button type="success" icon="ios-camera"  @click="takePhoto()">拍照</Button>
      <Button type="error" icon="ion-close-round"  @click="resetPhoto()">重置</Button>
      <Button type="info" icon="ion-upload"  @click="uploadPhoto()">上传</Button>
        </Row>
    </Modal>
  </div>
</template>
<script>
import Cookies from 'js-cookie'
import api from '../../api/api'
export default {
  name: 'login',
  data () {
    return {
      columns1: [
        {
          title: '用户名',
          key: 'uid'
        },
        {
          title: '相似得分',
          key: 'scores'
        },
        {
          title: '分组',
          key: 'group_id'
        }
      ],
      facedata: [],
      faceresult: false,
      token: '',
      imgData: null,
      loginModal: true,
      modal_loading: false,
      modal1: false,
      formValidate: {
        name: '',
        password: ''
      },
      ruleValidate: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码错误', trigger: 'blur' }],
        vcode: [{ required: true, message: '验证码错误', trigger: 'blur' }]
      }
    }
  },

  methods: {
    resetPhoto () {
      this.imgData = null
    },
    uploadPhoto () {
      var that = this
      var aCanvas = document.getElementById('canvas')
      var imgData = aCanvas.toDataURL('image/png')
      this.imgData = imgData.substr(22)
      console.log(imgData)
      api.uploadImage({sj: this.imgData}).then(function (res) {
        that.$Message.info({
          content: '系统返回共有' + res.result_num + '个相关数据',
          duration: 10,
          closable: true,
          onclose: function () {
            var that = this
            that.faceresult = true
            that.modal1 = false
          }
        })
        res.result.forEach(function (item, index) {
          that.facedata.push({ uid: item.uid,
            scores: item.scores,
            group_id: item.group_id})
        })
        that.faceresult = true
        that.modal1 = false
      })
    },
    takePhoto () {
      var video = document.getElementById('video')
      var aCanvas = document.getElementById('canvas')
      var ctx = aCanvas.getContext('2d')
      ctx.drawImage(video, 0, 0, 320, 240)
      var imgData = aCanvas.toDataURL('image/png')
      this.imgData = imgData.substr(22)
      this.$Message.success('拍照成功!')
    },

    faceLogin () {
      this.$Message.info('开始初始化摄像头!若浏览器提示，请点击允许！')
      this.initCamera()
      this.modal1 = true
    },
    initCamera () {
      var that = this
      this.imgData = null
      var video = document.getElementById('video')
      console.log(video)
      navigator.getUserMedia = navigator.getUserMedia ||
                          navigator.webkitGetUserMedia ||
                          navigator.mozGetUserMedia ||
                          navigator.msGetUserMedia// 获取媒体对象（这里指摄像头）
      navigator.getUserMedia({video: true}, gotStream, noStream)// 参数1获取用户打开权限；参数二成功打开后调用，并传一个视频流对象，参数三打开失败后调用，传错误信息
      function gotStream (stream) {
        video.src = URL.createObjectURL(stream)
        console.log(stream)
        video.play()
        console.log(video)
        video.onerror = function () {
          stream.stop()
        }
        stream.onended = noStream
        video.onloadedmetadata = function () {
          that.$Message.success('摄像头打开成功！')
        }
      }
      function noStream (err) {
        alert(err)
      }
    },
    ok () {
      var that = this
      that.faceresult = true
      that.modal1 = false
    },
    cancel () {

    },
    handleSubmit (name) {
      // login
      this.$refs[name].validate(valid => {
        this.modal_loading = true
        setTimeout(() => {
          this.modal_loading = false
          if (valid) {
            this.$Message.success('登录成功!')
            Cookies.set('token', this.formValidate.password)
            this.$router.push('/index')
          } else {
            this.$Message.error('表单验证失败!')
            this.$Notice.warning({
              title: '登录提示',
              desc: '用户名/密码 随意输入...'
            })
          }
        }, 2000)
      })
    },
    toRegister () {
      this.$router.push('/register')
    }
  }
}
</script>
<style>
.display{
  display: block;
  margin-left: auto; margin-right: auto;
}
.nodisplay{
  display: none;
}
</style>


